package com.pascuit.gpxhandler.server.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pascuit.gpxhandler.client.BlobService;
import com.pascuit.gpxhandler.server.dao.UserDao;
import com.pascuit.gpxhandler.shared.dto.GpxInfoDto;

/**
 * 
 * @author Parant
 * 
 */
public class BlobServiceImpl extends RemoteServiceServlet implements BlobService {

	private static final long serialVersionUID = 1L;

	BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	@Override
	public String getBlobStoreUploadUrl() {
		return blobstoreService.createUploadUrl("/gpxhandler/app/fileUpload").replace("MX-50015612", "127.0.0.1");
	}

	public void removeFromBlobStore(String key) {
		blobstoreService.delete(new BlobKey(key));
	}

	public GpxInfoDto getGpxInfo(String id) {
		WebApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());

		UserDao userDao = (UserDao) applicationContext.getBean("userDao");
		return userDao.getByPrimaryKey(id);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
		blobstoreService.serve(blobKey, resp);
	}
}
